const express       = require('express');
const keys          = require('../../../libs/keys');
const crypto        = require('../../../libs/crypto-util');
const responseData  = require('../../../libs/response-data');
const log           = require('log4js').getLogger("access");
const Sequelize     = require('sequelize');
const sequelize     = require('../../../libs/db-sequelize-util');
const User = sequelize.define('user', {
    username : {type : Sequelize.STRING}, 
    password : {type : Sequelize.STRING},}, {
        freezeTableName : true,
        tableName : 'user_table',
        createdAt : false,
        updatedAt : false
    });

module.exports = function() {
    let apiUser = express.Router();
    
    

    apiUser.post('/login', (req, res)=>{

        console.log('before decrypt----> username : ', req.body.username, ' \n before decypt ---> password: ', req.body.password);
        let username = req.body.username;
        let password = req.body.password;

        User.findOne({
            where : {username : username},
        }).then(user => {
            console.log(user.get('password'));
            })
            .catch(err => {
                console.error('findOne error ---> ', err);
            });
              
        res.status(200).send(responseData.getResponse("0", "api for login", {})).end();
    });

    apiUser.post('/signin', checkSignInParams, (req, res)=>{
        let uname = req.body.username;
        let upass = req.body.password;

        User.findOne({
            where : {username : uname},
        }).then(user=> {
            if (user) {
                let info = uname + ": 已注册，请登录";
                res.status(200).send(responseData.getResponse("1", info, {})).end();
            } else {
                sequelize.sync()
                    .then(() => User.create({
                        username: uname,
                        password: upass
                    }))
                    .then(jane => {
                        console.log(jane.toJSON());
                        res.status(200).send(responseData.getResponse("0", '注册成功', jane.toJSON())).end();
                    });
            }
        });

    });

    function checkSignInParams(req, res, next) {
        let uname = req.body.username;
        let upass = req.body.password;
        if (!uname) {
            return res.status(200).send(responseData.getResponse("1", '用户名缺失', {})).end();
        }
        if (!upass) {
            return res.status(200).send(responseData.getResponse("1", '密码缺失', {})).end();
        }
        next();
    }

    return apiUser;
}